﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoCadConvert
{
    public class HttpManager
    {
        static HttpManager()
        {
            foreach (SettingsProperty item in Properties.Settings.Default.Properties)
            {
                if (item.PropertyType.FullName == "System.Collections.Specialized.StringCollection")
                {
                    StringCollection children = Properties.Settings.Default[item.Name] as StringCollection;
                    if (children.Count>0 && item.Name == "后台地址")
                        s_homeurl = children[0];
                    else if (children.Count > 0 && item.Name == "上传地址")
                        s_fileupload = children[0];
                    else if (children.Count > 0 && item.Name == "下载地址")
                        s_filestore = children[0];
                }
            }
        }
        #region 地址
        //https://192.168.0.149:8071
        //https://www.sz-swjx.cn
        //http://192.168.0.242:8071
        //http://192.168.0.149:8071
        //https://www.sz-swjx.cn
        public static string s_homeurl = "";
        public static string s_gettoken = "/dm/store/gettoken";
        public static string s_output = "/dm/task/output";
        public static string s_process = "/dm/task/process";
        public static string s_filter2 = "/dm/task/filter2";
        public static string s_login = "/dm/user/login";
        public static string s_logout = "/dm/user/logout";
        public static string s_dwgsearch = "/dm/legend/search";
        public static string s_dwgdetail = "/dm/legend/detail";
        public static string s_cataloglevel = "/dm/catalog/level";
        public static string s_catalogall = "/dm/catalog/all";
        //七牛
        //"http://up.qiniu.com";
        //"http://192.168.0.208:8090/upload";
        //"https://up.my-best-home.cn/upload"
        public static string s_fileupload = "";
        //"https://dm.my-best-home.cn/";
        //"https://files.my-best-home.cn/"
        public static string s_filestore = "";

        #endregion

        #region 数据格式
        #region 响应数据
        public class ResponseData
        {
            public class Data
            {
                public string domain="";
                public string token = "";
            }
            public int code=0;
            public Data data=null;
            public string msg = "";
        }
        public class Qiniu_Response
        {
            public string hash="";
            public string key="";
        }
        public class Upload_Response
        {
            public class Data
            {
                public string path = "";
                public string domain = "";
            }
            public int code = 0;
            public Data data = null;
            public string msg = "";
        }
        public class TaskFilter_Response
        {
            public class Plan
            {
                public string executorName = "";
                public string pakUrl = "";
                public string verifyId = "";
                public string executorId = "";
                public string previewFileUrl = "";
                public string outputFileUrl = "";
                public int planId=0;
                public int priv=0;
                public int type=0;
                public int status=0;
                public string pakThumbUrl = "";
            }
            public class TaskItem
            {
                public int isCAD=0;
                public string buildingProvince = "";
                public string finishTime = "";
                public string houseId = "";
                public string houseType = "";
                public string creatorId = "";
                public string creatorName = "";
                public string description = "";
                public string[] taskInput=null;
                public string type = "";
                public Plan[] planInfo = null;
                public string houseDescription = "";
                public string houseName = "";
                public string buildingName = "";
                public string createTime = "";
                public string buildingCity = "";
                public string name = "";
                public double houseArea =0;
                public string buildingLocation = "";
                public int id =0;
                public string buildingDistrict = "";
                public int status = 0;
            }
            public class Task
            {
                public int count=0;
                public TaskItem[] tasks=null;
            }
            public int code=0;
            public Task data=null;
            public string msg = "";
        }
        public class UserLogin_Response
        {
            public class Data
            {
                public string homeUrl = "";
                public int[] roleIds=null;
                public string account = "";
                public string token = "";
            }
            public int code=0;
            public Data data=null;
            public string msg = "";
        }
        public class UserLogout_Response
        {
            public class Data
            {
                public string homeUrl = "";
                public int[] roleIds = null;
                public string account = "";
                public string token = "";
            }
            public int code = 0;
            public Data data = null;
            public string msg = "";
        }
        public class CatalogLevel_Response
        {
            public class Catalog
            {
                public string classify="";
                public string code = "";
                public int level = 0;
                public string name = "";
                public bool hasNext = false;
                public string iconUrl = "";
                public int id = 0;
            }
            public class CatalogData
            {
                public Catalog[] catalogs = null;
                public int count = 0;
            }
            public int code=0;
            public string msg = "";
            public CatalogData data = null;
        }
        public class LegendSearch_Response
        {
            public class Legend
            {
                public string[] typeName = null;
                public string creatorId = "";
                public string description = "";
                public string explainUrl = "";
                public string dwgMd5 = "";
                public string sizelong = "";
                public string[] typeCode = null;
                public string explainMd5 = "";
                public string createTime = "";
                public string updateTime = "";
                public string name = "";
                public string width = "";
                public string dwgUrl = "";
                public string sn = "";
                public string height = "";
            }
            public class LegendData
            {
                public Legend[] legends = null;
                public int count = 0;
            }
            public int code = 0;
            public string msg = "";
            public LegendData data = null;
        }
        public class LegendDetail_Response
        {
        }
        #endregion
        #region 请求数据
        public class UserLogin_Request
        {
            public string account = "";
            public string password = "";
            public bool isWeb = false;
            public new string ToString()
            {
                return "account=" + account + "&password=" + password + "&isWeb=" + (isWeb ? 1 : 0);
            }
        }
        public class UserLogout_Request
        {
            public string account = "";
            public string token = "";
            public string sign = "";
            public bool isWeb = false;
            public new string ToString()
            {
                return "account=" + account + "&token=" + token + "&sign=" + sign + "&isWeb=" + (isWeb ? 1 : 0);
            }
        }
        public class TaskFilter_Request
        {
            public string account = "";//登录账号(BASE64加密)
            public int type=0;//任务类型
            public int status=0;//任务状态
            public string value = "";//{'name':'名称描述模糊匹配','buildingName':'楼盘名称','province':'省中文名','city':'市中文名'}
            public int pageNum=0;//分页第几页
            public int pageSize=0;//每页大小
            public string token = "";//登录验证token
            public int cad=0;//0或不填只查bsp 1查cad 2查全部
            public string sign = "";//MD5验证签名，加密原始值为filter2status#{status}type#{type}value#{value}或者filter2status#{status}type#{type}value0000
            public bool enableOther=false;//是否允许查出自己没参与的任务 1为允许 不填或者其它值为不允许
            public new string ToString()
            {
                return "account=" + account + "&type=" + type + "&status=" + status + "&value=" + value + "&pageNum=" + pageNum + "&pageSize=" + pageSize + "&token=" + token + "&cad=" + cad + "&sign=" + sign;
            }
        }
        public class TaskOutput_Request
        {
            public string account = "";
            public int planId=0;
            public string output = "";
            public string preview = "";
            public string info = "";
            public string token = "";
            public string sign = "";
            public new string ToString()
            {
                return "account=" + account + "&planId=" + planId + "&output=" + output + "&preview=" + preview + "&info=" + info + "&token=" + token + "&sign=" + sign;
            }
        }
        public class TaskProcess_Request
        {
            public string account = "";
            public string planIds = "";
            public string newStatuses = "";
            public string token = "";
            public string sign = "";
            public new string ToString()
            {
                return "account=" + account + "&planIds=" + planIds + "&newStatuses=" + newStatuses + "&token=" + token + "&sign=" + sign;
            }
        }
        public class CatalogLevel_Request
        {
            public string account="";
            public string token = "";
            public string sign = "";
            public string code = "";
            public string classify = "";
            public new string ToString()
            {
                return "account=" + account + "&token=" + token + "&sign=" + sign + "&code=" + code + "&classify=" + classify;
            }
        }
        public class LegendSearch_Request
        {
            public string account="";
            public string value = "";
            public int pageNum = 0;
            public int pageSize = 0;
            public string token = "";
            public string sign = "";
            public new string ToString()
            {
                return "account=" + account + "&value=" + value + "&pageNum=" + pageNum + "&pageSize=" + pageSize + "&token=" + token + "&sign=" + sign;
            }
        }
        public class LegendDetail_Request
        {
            public string account="";
            public string sn = "";
            public string token = "";
            public string sign = "";
            public new string ToString()
            {
                return "account=" + account+ "&sn=" +sn+ "&token=" +token+ "&sign="+sign;
            }
        }
        #endregion
        #endregion

        #region 请求接口
        public static string GetToken()
        {
            try
            {
                string getToken = "account=" + LoginInfo.instance().userNameBase64
                + "&info=" + ""
                + "&token=" + LoginInfo.instance().token
                + "&singn=" + Md5Helper.GetStrMd5_32X("gettokeninfo");
                string response = HttpHelper.HttpPost(s_homeurl + s_gettoken, getToken);
                ResponseData ret = JsonConvert.DeserializeObject<ResponseData>(response);
                if (ret.code == 1001)
                    return ret.data.token;
                else
                    return "";
            }
            catch(Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
                return "";
            }
        }
        public static string TaskOutput(int planid, string output, string preview)
        {
            string response = "";
            try
            {
                response = HttpHelper.HttpPost(s_homeurl + s_output, new TaskOutput_Request()
                {
                    account = LoginInfo.instance().userNameBase64,
                    planId = planid,
                    output = output,
                    preview = preview,
                    info = "{}",
                    token = LoginInfo.instance().token,
                    sign = Md5Helper.GetStrMd5_32X("outputplanId" + planid + "output" + output + "preview" + preview),
                }.ToString());
                return response;
            }
            catch(Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
                return "";
            }
        }
        public static string TaskProcess(int[] planid, int[] statuses)
        {
            string response = "";
            try
            {
                string plan = JsonConvert.SerializeObject(planid);
                string status = JsonConvert.SerializeObject(statuses);
                response = HttpHelper.HttpPost(s_homeurl + s_process, new TaskProcess_Request()
                {
                    account = LoginInfo.instance().userNameBase64,
                    planIds = plan,
                    newStatuses = status,
                    token = LoginInfo.instance().token,
                    sign = Md5Helper.GetStrMd5_32X("processplanIds" + plan + "newStatuses" + status),
                }.ToString());
                return response;
            }
            catch(Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
                return "";
            }
        }
        public static TaskFilter_Response TaskFilter(int type, int status)
        {
            string response = "";
            try
            {//type:1-2d,2-硬装,3-软装（task-plan一对多）
                response = HttpHelper.HttpPost(s_homeurl + s_filter2, new TaskFilter_Request()
                {
                    account = LoginInfo.instance().userNameBase64,
                    type = type,
                    status = status,
                    value = "{}",
                    cad = 1,
                    pageNum = 1,
                    pageSize = 10,
                    token = LoginInfo.instance().token,
                    sign = Md5Helper.GetStrMd5_32X("filter2status" + status + "type" + type + "value{}")
                }.ToString());
                return JsonConvert.DeserializeObject<TaskFilter_Response>(response);
            }
            catch(Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
                return null;
            }
        }
        public static UserLogin_Response AutoLogin(string account,string password)
        {
            string response = "";
            try
            {
                response = HttpHelper.HttpPost(s_homeurl + s_login, new UserLogin_Request()
                {
                    account = account,
                    password = password,
                    isWeb = false
                }.ToString());
                return JsonConvert.DeserializeObject<UserLogin_Response>(response);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
                return null;
            }
        }
        public static UserLogin_Response UserLogin(string user,string password)
        {
            string response = "";
            try
            {
                response = HttpHelper.HttpPost(s_homeurl+ s_login, new UserLogin_Request()
                {
                    account = LoginInfo.instance().userNameBase64,
                    password = Md5Helper.GetStrMd5_32X(password + user),
                    isWeb = false
                }.ToString());
                UserLogin_Response ret = JsonConvert.DeserializeObject<UserLogin_Response>(response);
                LoginInfo.instance().userNameBase64 = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(user));
                LoginInfo.instance().passwordMD5 = Md5Helper.GetStrMd5_32X(password + user);
                return ret;
            }
            catch(Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
                return null;
            }
        }
        public static UserLogout_Response UserLogout()
        {
            string response = "";
            try
            {
                response = HttpHelper.HttpPost(s_homeurl + s_logout, new UserLogout_Request()
                {
                    account = LoginInfo.instance().userNameBase64,
                    token = LoginInfo.instance().token,
                    sign = Md5Helper.GetStrMd5_32X("logoutaccount"+ LoginInfo.instance().userNameBase64),
                    isWeb = false
                }.ToString());
                return JsonConvert.DeserializeObject<UserLogout_Response>(response);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
                return null;
            }
        }

        public static CatalogLevel_Response Catalog_Level(string code,string classify)
        {
            string response = "";
            try
            {
                response = HttpHelper.HttpPost(s_homeurl + s_cataloglevel, new CatalogLevel_Request()
                {
                    account = LoginInfo.instance().userNameBase64,
                    token = LoginInfo.instance().token,
                    sign = Md5Helper.GetStrMd5_32X("searchCatalog"+ code+ classify),
                    code = code,
                    classify = classify
                }.ToString());
                return JsonConvert.DeserializeObject<CatalogLevel_Response>(response);
            }
            catch(Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
                return null;
            }
        }
        public static void Catalog_All()
        {

        }
        public static LegendSearch_Response Legend_Search(string typecode,string classify,int page)
        {
            string response = "";
            try
            {
                string value = JsonConvert.SerializeObject(new { name = "", typeCode = typecode, classify = classify, legendType ="0" });
                response = HttpHelper.HttpPost(s_homeurl + s_dwgsearch, new LegendSearch_Request()
                {
                    account = LoginInfo.instance().userNameBase64,
                    value=value,
                    pageNum= page,
                    pageSize=10,
                    token = LoginInfo.instance().token,
                    sign = Md5Helper.GetStrMd5_32X("searchvalue" + value),
                }.ToString());
                return JsonConvert.DeserializeObject<LegendSearch_Response>(response);
            }
            catch(Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
                return null;
            }
        }
        public static LegendDetail_Response Legend_Detail(string sn)
        {
            string response = "";
            try
            {
                response = HttpHelper.HttpPost(s_homeurl + s_dwgdetail, new LegendDetail_Request()
                {
                    account = LoginInfo.instance().userNameBase64,
                    sn = sn,
                    token = LoginInfo.instance().token,
                    sign = Md5Helper.GetStrMd5_32X("detailsn" + sn),
                }.ToString());
                return JsonConvert.DeserializeObject<LegendDetail_Response>(response);
            }
            catch(Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
                return null;
            }
        }
        public static string Upload(string newFileName,string filePath)
        {
            string response = "";
            try
            {
                if (HttpManager.s_fileupload.Contains("qiniu"))
                {
                    string uploadToken = HttpManager.GetToken();
                    if (!string.IsNullOrEmpty(uploadToken))
                    {//qiniu
                        response = HttpHelper.HttpUploadFile(HttpManager.s_fileupload, uploadToken, newFileName, filePath);
                        Qiniu_Response ret = JsonConvert.DeserializeObject<Qiniu_Response>(response);
                        return HttpManager.s_filestore + ret.key;
                    }
                    else
                    {
                        DwgConvert.PutMessage("上传Token获取失败");
                        return "";
                    }
                }
                else
                {
                    response = HttpHelper.HttpUploadFile(HttpManager.s_fileupload, "", newFileName, filePath);
                    Upload_Response ret =JsonConvert.DeserializeObject<Upload_Response>(response);
                    if (ret!=null&&ret.code == 1001)
                        return Path.Combine(ret.data.domain, ret.data.path);
                    else
                        return "";
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);
                return "";
            }
        }
        #endregion
    }
}
